/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package percussiongenerator.gui;

import java.awt.Dimension;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.NumberFormat;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import percussiongenerator.icons.IconLoader;
import percussiongenerator.sound.IMidiPlayer;
import percussiongenerator.sound.ITimeListener;

/**
 * This panel contains buttons to use a midiplayer.
 * This class listens to the time of the midiplayer.
 * @author jannes
 */
public class PlayerPanel extends JPanel implements ITimeListener{
    private IMidiPlayer midiPlayer;
    private JLabel timeLabel;
    private NumberFormat format;
    public PlayerPanel(IMidiPlayer player){
        midiPlayer = player;
        midiPlayer.addTimeListener(this);
        format = NumberFormat.getIntegerInstance();
        format.setMinimumIntegerDigits(2);
        IconLoader iconLoader = new IconLoader();
        final JButton btnPlayPause = new JButton(iconLoader.loadIcon("play.png"));
        btnPlayPause.setFocusable(false);
        /*
        if(player.isPlaying()){
            btnPlayPause.setText("||");
        }else{
            btnPlayPause.setText(">");
        }
         */
        btnPlayPause.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if(btnPlayPause.getText().equals(">")){                    
                    midiPlayer.play();
                    btnPlayPause.setText("||");
                }else{
                    midiPlayer.pause();
                    btnPlayPause.setText(">");
                }
            }
        });
        add(btnPlayPause);
        //JButton btnStop = new JButton("[]");
        JButton btnStop = new JButton(iconLoader.loadIcon("stop.png"));
        btnStop.setFocusable(false);
        btnStop.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                midiPlayer.stop();
                btnPlayPause.setText(">");
            }
        });
        add(btnStop);
        timeLabel = new JLabel("");
        this.add(timeLabel);
    }

    public void timeUpdated(long time) {
        time += midiPlayer.getSoundDelay();
        long milliseconds = time/1000000l;
        int seconds = (int) ((milliseconds / 1000) % 60);
        int minutes = (int) ((milliseconds / 1000) / 60);
        int hours   = (int) ((milliseconds / 1000) / 3600);
        timeLabel.setText("" + hours + ":" + format.format(minutes) + ":" + format.format(seconds) + "." + format.format((milliseconds%1000)/10));
    }

}
